#!/usr/bin/env python

from liwe.module import LiweModule

class Stats ( LiweModule ):
	def __init__ ( self, liwe ):
		super ( Stats, self ).__init__ ( liwe, "stats" )

		self.dbm = self.liwe.dbm


	def log ( self, module, id_ref = None, event = 'view', extra = '', uid = 0 ):

		values = {
			'module': module,
			'id_ref': id_ref,
			'event': event,
			'created': '*NOW()',
			'uid' : uid,
			'extra': extra
		}

		self.dbm.insert ( 'stats_log', values )

	def list ( self, module = '', id_ref = '', event = '', log_start = '', log_end = '', order = 'created', uid = -1 ):
		conds = []

		if module: conds.append ( "module = '%s'" % module )
		if id_ref: conds.append ( "id_ref = '%s'" % id_ref )
		if event: conds.append ( "event = '%s'" % event )
		if log_start: conds.append ( "created >= '%s'" % log_start )
		if log_end: conds.append ( "created <= '%s'" % log_end )
		if uid != -1: conds.append ( "uid = %s" % uid )

		conds = ' AND '.join ( conds )
		extras = 'ORDER BY %s' % order

		rs = self.dbm.all_rows ( 'stats_log', '*', conds, extras = extras )
		if not rs: rs = []

		return rs

	def reset ( self, module = '', id_ref = '', event = '', full = False ):

		if not module and not id_ref and not event: return false

		conds = []

		if module: conds.append ( "module = '%s'" % module )
		if id_ref: conds.append ( "id_ref = '%s'" % id_ref )
		if event: conds.append ( "event = '%s'" % event )

		conds = ' AND '.join ( conds )

		ids = self.dbm.all_rows ( 'stats_event', [ 'id' ], conds = conds )

		conds = 'id in (%s)' % ','.join ( ids )
		
		self.dbm.delete ( 'stats_log', conds = conds )

	def archive ( self ):
		for ex in [ 
			'DROP TABLE IF EXISTS stats_work',
			'CREATE TABLE stats_swap LIKE stats_log',
			'RENAME TABLE stats_log  TO stats_work, stats_swap TO stats_log',
			'ALTER TABLE stats_work ADD INDEX ( module )',
			'ALTER TABLE stats_work ADD INDEX ( event )',
			'ALTER TABLE stats_work ADD INDEX ( created )' ]:

			self.dbm.execute ( ex )


		#import datetime
		
		#curr_date = datetime.datetime.now ().strftime ( "%Y-%m-%d %H:%M:%S" )

		# this function should be called every day to archive the previous day stats
		fields = [ 'module', 'id_ref', 'event', 'DATE( created ) as day', 'HOUR( created ) as hour', 'COUNT( 1 ) as hits', 'uid' ]
		conds = "" #<= DATE_ADD( '%s', INTERVAL -%s MINUTE )" % ( curr_date, self.cfg.get ( "archive.interval", 60 ) )
		extras = 'GROUP BY module, id_ref, event, DATE( created ), HOUR( created ), uid'

		cur = self.dbm.select ( 'stats_work', fields, conds, extras = extras )
		if cur:
			for row in cur:
				_conds = []
				for k in [ "module", "id_ref", "event", "day", "hour", "uid" ]:
					_conds.append ( "%s = '%s'" % ( k, row [ k ] ) )

				_conds = ' AND '.join ( _conds )
				
				vals = self.dbm.single_row ( "stats_archive", "hits", _conds )

				if vals:
					self.dbm.update ( "stats_archive", { "hits" : row [ 'hits' ] + vals [ 'hits' ] }, _conds )
				else:
					self.dbm.insert ( 'stats_archive', row )

		#	self.dbm.delete ( 'stats_log', "created " + conds )
		self.dbm.execute ( 'DROP TABLE IF EXISTS stats_work' )

	def data ( self, module = '', id_ref = '', event = '', log_start = '', log_end = '', log_type = 'day' ):
		
		conds = []

		if module: conds.append ( "module = '%s'" % module )
		if id_ref:
			id_ref = id_ref.split ( ',' )
			conds.append ( "id_ref in ( %s )" % ','.join ( [ "'%s'" % x for x in id_ref ] ) )

		if event and event != '__all': conds.append ( "event = '%s'" % event )
		if log_start: conds.append ( "date( created ) >= '%s'" % log_start )
		if log_end: conds.append ( "date( created ) <= '%s'" % log_end )

		conds = ' AND '.join ( conds )

		if log_type == 'day':
			period = 'date( created )'
		elif log_type == 'month':
			period = 'extract( year_month from created )'
		elif log_type == 'year':
			period = 'year( created )'
		elif log_type == 'weekday':
			period = 'weekday( created )'
		elif log_type == 'week':
			period = 'week( created )'
		elif log_type == 'hour':
			period = 'hour( created )'
		else:
			return False
	
		fields = [ 'count( 1 ) as value', '%s as period' % period ]
		groups = [ 'period' ]

		if event == '__all':
			fields.append ( 'event' )
			groups.append ( 'event' )

		data = self.dbm.all_rows ( 'stats_log', fields, conds = conds, extras = 'group by ' + ','.join ( groups ) + ' order by period', debug = self.debug () )

		return data
